//main
import sha256 from "crypto-js/sha256";
import aes from "crypto-js/aes";
//data
import store from "../../store/store";
import { addChat } from "../../store/actions/chat";
//funcs
import api from "../../api/apiFuncs";
import { msgTypes } from "../../api/api";

const CryptoJS = require("crypto-js");

function createHash(value) {
  return sha256(value).toString();
}

function enc(data, key) {
  return aes.encrypt(data, key).toString();
}

function dec(data, key) {
  return aes.decrypt(data, key).toString(CryptoJS.enc.Utf8);
}

//join to chat if WS connected and chat isn't already exists
function newChat(key, wsstatus) {
  const storage = store.getState();
  if (wsstatus) {
    if (!storage.chats[createHash(key)]) {
      api[msgTypes.subscribeToChat](createHash(key));
      store.dispatch(addChat(key));
    } else {
      console.log("chat already exists");
    }
  } else {
    throw new Error("wsstatus: " + wsstatus);
  }
}

function sendMessage(chatID, key, image, message, wsstatus) {
  const bad = /^(\n){1,}$/;
  if (wsstatus) {
    if (message && chatID && !bad.test(message)) {
      const encmsg = enc(message, key);
      const encimg = enc(image, key);
      api[msgTypes.sendMessage](chatID, encimg, encmsg);
    }
  } else {
    throw new Error("wsstatus: " + wsstatus);
  }
}

export { createHash, enc, dec, sendMessage, newChat };
